<template>
  <div>
    <ZgDialog
      :width="view.width"
      :top="view.top"
      :title="view.title"
      :showFooter="view.showFooter"
      v-model="visible"
      @ok="onOk"
      @cancel="onCancel"
    >
      <div v-if="initLoading">
        正在初始化配置数据...
      </div>
      <div v-else>
        <div v-if="!hasInit">
          初始化配置数据失败
        </div>
        <div :style="{padding:`${layout.视图边距}px`}">
          <a-table
            size="small"
            bordered
            :customHeaderRow="()=>{return { style: { background: '#f2f2f2' } }}"
            :pagination="false"
            :scroll="{ y: 400 }"
            :dataSource="tableData"
            rowKey="id"
          >
            <a-table-column
              key="formName"
              width="350"
              title="表单名称">
              <template slot-scope="text, record, index">
                <a-select
                  v-model="record.formId"
                  placeholder="请选择表单"
                  style="width: 100%"
                  showSearch
                  :filterOption="false"
                  @change="(value) => handleFormChange(value, index)"
                  @search="handleFormSearch"
                >
                  <a-select-option
                    v-for="option in formOptions"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </a-select-option>
                </a-select>
              </template>
            </a-table-column>
            <a-table-column
              key="viewName"
              width="350"
              title="视图名称">
              <template slot-scope="text, record, index">
                <a-select
                  v-model="record.viewId"
                  placeholder="请选择视图"
                  style="width: 100%"
                  :options="getViewOptionsForRow(record.id)"
                  showSearch
                  @change="(value) => handleViewChange(value, index)"
                >
                </a-select>
              </template>
            </a-table-column>
            <a-table-column
              key="handle"
              width="100"
              title="操作">
              <template slot-scope="text, record, index">
                <a-button
                  type="primary"
                  size="small"
                  icon="plus"
                  @click="addRow"
                >
                  添加
                </a-button>
                <a-button
                  v-if="tableData.length > 1"
                  type="danger"
                  size="small"
                  icon="delete"
                  style="margin-left: 8px"
                  @click="deleteRow(index)"
                >
                  删除
                </a-button>
              </template>
            </a-table-column>
          </a-table>
        </div>
      </div>
    </ZgDialog>
  </div>
</template>
<script>

export default {

  data () {
    return {
      visible: false,
      hasInit: true,
      initLoading: false,
      layout: {
        视图边距: 0
      },
      recordObj: {},
      view: {
        width: '800px',
        top: '5%',
        title: '表单配置',
        showFooter: true
      },
      tableData: [
        {
          id: 1,
          formId: '',
          formName: '',
          viewId: '',
          viewName: '',
          isFromBackend: false
        }
      ],
      formOptions: [],
      allFormOptions: [], // 存储所有表单选项
      rowViewOptions: {} // { rowId: [viewOptions] }
    }
  },
  methods: {
    open (record) {
      this.recordObj = record
      this.$http.post('/zg-autoflow/autoFlow/step/formList', { stepId: this.recordObj.id }, (data) => {
        // 如果有数据则直接使用返回的数据，不添加默认行
        if (data && data.length > 0) {
          this.tableData = data.map((item, index) => ({
            id: index + 1,
            formId: item.formId || '',
            formName: item.formName || '',
            viewId: item.viewId || '',
            viewName: item.viewName || '',
            isFromBackend: true
          }))
          // 为每个已有的表单数据加载对应的视图选项
          this.tableData.forEach((item, index) => {
            if (item.formId) {
              this.$http.post('/zg-autoform/view/list', { formId: item.formId }, (viewData) => {
                const rowId = item.id
                this.$set(this.rowViewOptions, rowId, viewData.map(viewItem => ({
                  label: viewItem.name,
                  value: viewItem.id
                })))
              })
            }
          })
        } else {
          // 没有后端数据时添加一行默认的空行
          this.tableData = [{
            id: 1,
            formId: '',
            formName: '',
            viewId: '',
            viewName: '',
            isFromBackend: false
          }]
        }
       })
       // 初始化时加载所有表单数据
       this.$http.post('/zg-autoform/form/list', { name: '' }, (data) => {
         this.allFormOptions = data.map(item => ({
           label: item.name,
           value: item.id
         }))
         this.formOptions = [...this.allFormOptions] // 默认显示所有选项
       })
      this.visible = true
    },
    onOk () {
      // 检查用户新增的行是否有未完成的配置
      const userRows = this.tableData.filter(item => !item.isFromBackend)
      const incompleteRows = []
      userRows.forEach((item, index) => {
        const actualRowNumber = this.tableData.indexOf(item) + 1
        if (!item.formId && !item.viewId) {
          // 两个都没选择，跳过这一行（允许空行存在）
          return
        }
        if (!item.formId) {
          incompleteRows.push(`第${actualRowNumber}行：请选择表单名称`)
        }
        if (!item.viewId) {
          incompleteRows.push(`第${actualRowNumber}行：请选择视图名称`)
        }
      })
      if (incompleteRows.length > 0) {
        this.$message.error(`配置不完整：\n${incompleteRows.join('\n')}`)
        return
      }
      // 过滤出所有有效的配置数据（包括回显数据和新增数据）
      const validFormInfo = this.tableData.filter(item => item.formId && item.viewId)
      if (validFormInfo.length === 0) {
        this.$message.error('请至少配置一组有效的表单名称和视图名称！')
        return
      }
      // 保存配置数据
      const saveData = {
        formInfo: validFormInfo.map(item => ({
          formId: item.formId,
          viewId: item.viewId
        })),
        stepId: this.recordObj.id
      }
      this.$http.post('/zg-autoflow/autoFlow/step/addStepForm', saveData, () => {
        this.$message.success('配置保存成功！')
        this.resetViewOptions()
        this.visible = false
      }, (error) => {
        console.error('保存配置失败:', error)
        this.$message.error('保存配置失败，请重试！')
      })
    },
    onCancel () {
      this.resetViewOptions()
      this.visible = false
    },
    resetViewOptions () {
      // 重置所有行的视图选项
      this.rowViewOptions = {}
      // 重置表格数据中的视图相关字段
      this.tableData.forEach(item => {
        if (!item.isFromBackend) {
          item.viewId = ''
          item.viewName = ''
        }
      })
    },
    handleViewChange (value, index) {
      this.tableData[index].viewId = value
      console.log('视图选择变化:', value, index)
    },
    addRow () {
      const newId = this.tableData.length > 0 ? Math.max(...this.tableData.map(item => item.id)) + 1 : 1
      this.tableData.push({
        id: newId,
        formId: '',
        formName: '',
        viewId: '',
        viewName: '',
        isFromBackend: false
      })
    },
    deleteRow (index) {
      if (this.tableData.length > 1) {
        this.tableData.splice(index, 1)
      }
    },
    handleFormChange (value, index) {
      if (!value || index < 0 || index >= this.tableData.length) {
        console.warn('无效的表单ID或索引')
        return
      }
      this.tableData[index].formId = value
      this.tableData[index].viewId = ''
      this.tableData[index].viewName = ''
      this.$http.post('/zg-autoform/view/list', { formId: value }, (data) => {
        const rowId = this.tableData[index].id
        this.$set(this.rowViewOptions, rowId, data.map(item => ({
          label: item.name,
          value: item.id
        })))
       })
    },
    // 获取指定行的视图选项
    getViewOptionsForRow (rowId) {
      return this.rowViewOptions[rowId] || []
    },
    handleFormSearch (value) {
      if (value && value.trim()) {
        const searchValue = value.trim().toLowerCase()
        this.formOptions = this.allFormOptions.filter(option => {
          if (!option || !option.label) return false
          // 只搜索标签，不搜索ID值
          return option.label.toLowerCase().includes(searchValue)
        })
      } else {
        // 清空搜索时，重置为所有选项并强制更新
        this.$set(this, 'formOptions', [...this.allFormOptions])
      }
      // 强制更新视图
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
